#! /usr/bin/env python2.4
# -*- mode: python -*-
###
#
# (c) 2000-2007 Wijnand Modderman <wijnand at tehmaze dot com>
# All rights reserved. See docs/LICENSE
#
###

__revision__ = '$Hg$'

# system imports
import sys, os
from optparse import OptionParser, make_option

# fix include dirs
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))+os.sep+'lib')

def parse_opt():
    usage = "usage: %prog [options]"
    optionList = [
        make_option('-d', '--daemon',  help='Run the bot in the background [default]', action='store_true', dest='daemon', default=False),
        make_option('-f', '--fg',      help='Run the bot in the foreground', action='store_false', dest='daemon'),
        make_option('-D', '--debug',   help='Turn on debugging output (implies -v)', action='store_true', dest='verbose', default=False),
        make_option('-q', '--quiet',   help='Turn off most output', action='store_false', dest='verbose'),
        make_option('-v', '--verbose', help='Turn on verbose output', action='store_true', dest='verbose', default=False),
        make_option('-w', '--workdir', help='Change working directory before starting, if for example your config/ directory is living somewhere else on the system'),
    ]
    parser = OptionParser(usage=usage, option_list=optionList)
    (options, args) = parser.parse_args(sys.argv)
    return options

def daemonize():
    # do the UNIX double-fork magic, see Stevens' "Advanced 
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    try: 
        pid = os.fork() 
        if pid > 0:
            # exit first parent
            sys.exit(0) 
    except OSError, e: 
        print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) 
        sys.exit(1)
    # decouple from parent environment
    #os.chdir("/") 
    os.setsid() 
    os.umask(0) 
    # do second fork
    try: 
        pid = os.fork() 
        if pid > 0:
            # exit from second parent, print eventual PID before
            print "DDB running in background with PID %d" % pid 
            fd=open('ddb.pid', 'w')
            fd.write(str(pid))
            fd.close()
            sys.exit(0) 
    except OSError, e: 
        print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) 
        sys.exit(1) 

if __name__ == '__main__':
    options = parse_opt()
    if options.workdir:
        os.chdir(options.workdir)
    # DDB imports
    from ddb.log import application, init, log, getLogFile
    import ddb.transport
    if options.verbose:
        options.daemon = False # no longer able to daemonize
    init(options)
    if options.daemon:
        daemonize()
        # now output all stdout/stderr to the logfile
        sys.stdout = getLogFile()
        sys.stderr = getLogFile()
    t = ddb.transport.transportManager
    #t.addTransport('irc', None)
    if not t.loadConfig('config/bot.ini'):
        sys.exit(1)
    t.startTransports()
    t.run()

# vim:ts=4:sw=4:et:
